﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.MemoryMappedFiles;

namespace InCom.Core.TerminalSend.MappedFile
{
    /// <summary>
    /// 用于操作磁盘文件的单例
    /// </summary>
    public class MemoryMappendFromFileOperater : MemoryMappedFileOperater
    {
        private static MemoryMappendFromFileOperater instance = null;

        /// <summary>
        ///  提供文件共享实例
        /// </summary>
        public new static MemoryMappendFromFileOperater Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MemoryMappendFromFileOperater();
                    instance.CreateOrGetFile();
                }
                return instance;
            }
        }

        


        protected override void CreateOrGetFile()
        {

            FineName = "磁盘共享文件";

            #region 单进程文件
            string iofile = AppDomain.CurrentDomain.BaseDirectory + FineName;
            System.IO.MemoryMappedFiles.MemoryMappedFile file = null;

            try
            {
                //尝试先打开共享文件,如果文件不存在则创建 新文件
                file = MemoryMappedFile.OpenExisting(FineName);
             }
            catch (FileNotFoundException)
            {
                if (!System.IO.File.Exists(iofile))
                {
                    //文件流
                    System.IO.FileStream fs = new FileStream(iofile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

                    file = MemoryMappedFile.CreateFromFile(fs, FineName, Capacity, MemoryMappedFileAccess.ReadWrite, new MemoryMappedFileSecurity() { }, HandleInheritability.Inheritable, false);
                }
                else {
                    //如果文件存在则打开文件
                    System.IO.FileStream fs = new FileStream(iofile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    file = MemoryMappedFile.CreateFromFile(fs, FineName, Capacity, MemoryMappedFileAccess.ReadWrite, new MemoryMappedFileSecurity() { }, HandleInheritability.Inheritable, false);
                }
            
            }



            #endregion

            File = file;
            accessorView = file.CreateViewAccessor();

        }
    }
}
